﻿using System;
using System.IO;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace Events.Data
{
	public class CloudTemplateManager : TemplateManager
	{
		private CloudBlobClient cloudBlobClient;
		private CloudQueueClient cloudQueueClient;

		public CloudTemplateManager()
		{
			CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
			{
				configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
			});
			var cloudStorageAccount = CloudStorageAccount.FromConfigurationSetting("BlobStorageConnectionString");
			this.cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
			this.cloudQueueClient = cloudStorageAccount.CreateCloudQueueClient();
		}

		public override byte[] GetRegistrationConfirmationTemplate()
		{
			var blob = this.GetTemplateContainer().GetBlobReference("Anmeldebestaetigung.docx");
			return blob.DownloadByteArray();
		}

		public override void SendRegistration(Stream source, Guid missionId)
		{
			var targetFileName = string.Format("Anmeldebestaetigung_{0}.docx", missionId.ToString());
			var blob = this.GetTemplateContainer().GetBlobReference(targetFileName);
			blob.UploadFromStream(source);
		}

		public override void QueueRegistration(Guid missionId)
		{
			var queue = this.GetQueue();
			queue.AddMessage(new CloudQueueMessage(missionId.ToString()));
		}

		private CloudBlobContainer GetTemplateContainer()
		{
			return cloudBlobClient.GetContainerReference("templates");
		}

		private CloudQueue GetQueue()
		{
			var queue = cloudQueueClient.GetQueueReference("registrationqueue");
			queue.CreateIfNotExist();
			return queue;
		}
	}
}
